package model

import (
	"database/sql"
	"fmt"
	"github.com/pkg/errors"
	"github.com/valyala/fastjson"
	"strconv"
	"strings"
	"time"

	"github.com/tal-tech/go-zero/core/stores/sqlc"
	"github.com/tal-tech/go-zero/core/stores/sqlx"
	"github.com/tal-tech/go-zero/core/stringx"
	"github.com/tal-tech/go-zero/tools/goctl/model/sql/builderx"
)

var (
	procExecFieldNames          = builderx.RawFieldNames(&ProcExec{})
	procExecRows                = strings.Join(procExecFieldNames, ",")
	procExecRowsExpectAutoSet   = strings.Join(stringx.Remove(procExecFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
	procExecRowsWithPlaceHolder = strings.Join(stringx.Remove(procExecFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
)

type (
	ProcExecModel interface {
		Insert(data ProcExec, tx ...sqlx.Session) (sql.Result, error)
		FindOne(id int64) (*ProcExec, error)
		FindOneByProcInstId(procInstId int64) (*ProcExec, error)
		Update(data ProcExec, tx ...sqlx.Session) error
		Delete(id int64) error
	}

	defaultProcExecModel struct {
		conn  sqlx.SqlConn
		table string
	}

	ProcExec struct {
		Id         int64     `db:"id"`
		ProcInstId int64     `db:"proc_inst_id"`
		NodeInfos  string    `db:"node_infos"`
		Form       string    `db:"form"`
		Status     int64     `db:"status"` // 状态：0=关闭，1=开启
		CreateTime time.Time `db:"create_time"`
		UpdateTime time.Time `db:"update_time"`
	}
)

func NewProcExecModel(conn sqlx.SqlConn) ProcExecModel {
	return &defaultProcExecModel{
		conn:  conn,
		table: "`proc_exec`",
	}
}

// GetNodeInfoByStep 获取执行流中的一个节点，如果step越界则返回 err
func (m *ProcExec) GetNodeInfoByStep(step int) (*ProcExecNode, error) {
	nodeStr := fastjson.GetString([]byte(m.NodeInfos), strconv.Itoa(step))
	if nodeStr == "" {
		return nil, errors.New("step 越界")
	}
	node := &ProcExecNode{}
	if err := node.Parse(nodeStr); err != nil {
		return nil, errors.Wrap(err, "ProcExecNode反序列化失败")
	}
	return node, nil
}

func (m *defaultProcExecModel) Insert(data ProcExec, tx ...sqlx.Session) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?)", m.table, procExecRowsExpectAutoSet)
	var err error
	var ret sql.Result
	if tx != nil && len(tx) > 0 && tx[0] != nil {
		ret, err = tx[0].Exec(query, data.ProcInstId, data.NodeInfos, data.Form, data.Status)
	} else {
		ret, err = m.conn.Exec(query, data.ProcInstId, data.NodeInfos, data.Form, data.Status)
	}
	return ret, err
}

func (m *defaultProcExecModel) FindOne(id int64) (*ProcExec, error) {
	query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", procExecRows, m.table)
	var resp ProcExec
	err := m.conn.QueryRow(&resp, query, id)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultProcExecModel) FindOneByProcInstId(procInstId int64) (*ProcExec, error) {
	var resp ProcExec
	query := fmt.Sprintf("select %s from %s where `proc_inst_id` = ? limit 1", procExecRows, m.table)
	err := m.conn.QueryRow(&resp, query, procInstId)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultProcExecModel) Update(data ProcExec, tx ...sqlx.Session) error {
	query := fmt.Sprintf("update %s set %s where `id` = ? and `create_time` < ?", m.table, procExecRowsWithPlaceHolder)
	var err error
	if tx != nil && len(tx) > 0 && tx[0] != nil {
		_, err = tx[0].Exec(query, data.ProcInstId, data.NodeInfos, data.Form, data.Status, data.Id)
	} else {
		_, err = m.conn.Exec(query, data.ProcInstId, data.NodeInfos, data.Form, data.Status, data.Id)
	}
	return err
}

func (m *defaultProcExecModel) Delete(id int64) error {
	query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
	_, err := m.conn.Exec(query, id)
	return err
}
